from django.conf import settings
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .tasks import Photoshop_Touch
from .models import AllinpayImagesList
from .forms import ProfileForm, AvatarUploadForm
import os, time
import random, string


# Create your views here.
def has_chocode(len=3, level=0):
    """返回随机数"""
    chars = string.digits
    if level > 0:
        chars += string.ascii_letters
    if level > 1:
        chars += string.punctuation
    return "".join(random.choice(chars) for _ in range(len))


def has_fname(fn):
    """创建文件名"""
    x, y = os.path.splitext(fn)
    chars = has_chocode(3)
    return f'{time.strftime("%Y%m%d%H%M%S", time.localtime())}{chars}{y}'


def uploadViews(request):
    if request.method == "GET":
        kwargs = {}
        if request.GET.get("auth", None):
            kwargs["auth"] = request.GET.get("auth")
        if request.GET.get("name", None):
            kwargs["name"] = request.GET.get("name")
        if not kwargs:
            return JsonResponse(
                {
                    "status": False,
                    "message": "Not find 'name' or 'auth' in args of params",
                },
                safe=True,
            )
        r = AllinpayImagesList.objects.filter(**kwargs).values(
            "id", "name", "auth", "image"
        )
        # print(r)
        d = {"res": list(r), "status": True}
        return JsonResponse(d, safe=True)

    elif request.method == "POST":
        # 检测登录
        # if not request.user.id:
        #     d = {"message": "No Login User", "status": False}
        #     return JsonResponse(d, safe=True)
        # 序列化验证
        avatar_form = AvatarUploadForm(request.POST, request.FILES)
        if avatar_form.is_valid():
            profile = AllinpayImagesList()
            profile.auth = avatar_form.cleaned_data["auth"]
            profile.name = avatar_form.cleaned_data["name"]
            profile.image = avatar_form.cleaned_data["image"]
            profile.save()
            # print(1)
            ps = Photoshop_Touch(profile.name, profile.image.url)
            # print(2)
            d = {
                "code": avatar_form.cleaned_data["code"],
                "file": profile.image.url,
                "status": True,
                "ps": ps,
            }
            # print(3)
            return JsonResponse(d, safe=True)
        else:
            d = {"message": "ValidError", "status": False}
            return JsonResponse(d, safe=True)
